package org.finesys.common.core.support.io;

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

/**
 * yaml配置文件加载，一般配合@PropertySource使用
 */
public class YamlPropertiesSourceFactory extends DefaultPropertySourceFactory {

	@Override
	@NonNull
	public PropertySource<?> createPropertySource(@Nullable String name,@NonNull EncodedResource resource) throws IOException {
		String sourceName = name != null ? name : resource.getResource().getFilename();
		Properties propertiesFromYaml = loadYaml(resource);
		return new PropertiesPropertySource(sourceName, propertiesFromYaml);
	}

	private Properties loadYaml(EncodedResource resource) {
		YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
		factory.setResources(resource.getResource());
		factory.afterPropertiesSet();
		return factory.getObject();
	}

}
